package com.chenguo.gulimall.search.thread;

import java.util.concurrent.*;

public class CgThreadTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*
           方式 1 和方式 2：主进程无法获取线程的运算结果。不适合当前场景
           方式 3：主进程可以获取线程的运算结果，但是不利于控制服务器中的线程资源。
                  可以导致服务器资源耗尽。
           方式 4：通过如下两种方式初始化线程池
           Executors.newFiexedThreadPool(3);
           //或者
           new ThreadPoolExecutor(
          // 核心线程池 保持空闲数量    最大线程数
           corePoolSize, maximumPoolSize,
           //维持时间          时间单位
             keepAliveTime, TimeUnit unit
           //阻塞队列       线程工厂       拒绝策略
             , workQueue, threadFactory,handler);
         */

        //1. 继承Thread
        //new Thread01().start();

        //2.实现runnable接口
        //new Thread(new Runnable01()).start();

        //3.实现Callable接口
//        FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
//        new Thread(futureTask).start();

        //4.线程池
         executor.execute(new Runnable01());


         Future<Integer> submit = executor.submit(new Callable01());
         submit.get();


    }


    //1. 继承Thread
    public static class Thread01 extends Thread{

        @Override
        public void run() {
            System.out.println("当前线程:"+ Thread.currentThread().getName());
            int i = 10 / 2;
            System.out.println("运行结果" + i);
        }
    }

    //2.实现runnable接口
    public static class Runnable01 implements Runnable{

        @Override
        public void run() {
            System.out.println("当前线程:"+ Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果" + i);

        }
    }

    //3.实现Callable接口
    public static class Callable01 implements Callable<Integer>{

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }


    private static void threadPool() {

        ExecutorService threadPool = new ThreadPoolExecutor(
                200,
                10,
                10L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        //定时任务的线程池
        ExecutorService service = Executors.newScheduledThreadPool(2);
        Executors.newFixedThreadPool(5);//固定大小
        Executors.newScheduledThreadPool(5);//定时任务的线程池
        Executors.newSingleThreadExecutor();//单线程的线程池 后台从队列获取任务 挨个执行













    }
}
